In time, you will call me master -- Star Wars
https://leetcode.com/problems/closest-binary-search-tree-value/
parent_val
to store parent valueclosest_val
to store closest node# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
target = round(target)
parent_val = closest_val = root.val
while root:
if root.val < target:
root = root.right
elif root.val > target:
root = root.left
else:
return target
if root != None:
if abs(root.val-target) < abs(parent_val-target):
closest_val = root.val
parent_val = root.val
return closest_val